//
// Created by lee on 2024年1月24日 0024.
//

#include <stdbool.h>
#include "vmmath.h"

Add add(unsigned short add1, unsigned short add2) {
    Add a;
    a.S = 0;
    a.C = 0;
    bool is_first = true;
    int j1 = 0, j2 = 0;
    int a1 = add1, a2 = add2;
    while (a1 > 0) {
        a1 >>= 1;
        ++j1;
    }
    while (a2 > 0) {
        a2 >>= 1;
        ++j2;
    }
    int j = j1 > j2 ? j1 : j2;
    for (int i = 0; i < j || a.C == 1; ++i) {
        unsigned char add1_bit = (add1 >> i) & 1;
        unsigned char add2_bit = (add2 >> i) & 1;
        unsigned char S;
        unsigned char C;
        if (is_first) {
            S = add1_bit ^ add2_bit;
            C = add1_bit & add2_bit;
            is_first = false;
        } else {
            S = add1_bit ^ add2_bit ^ a.C;
            C = add1_bit & add2_bit | a.C & (add1_bit | add2_bit);
        }
        a.S += S << i;
        a.C = C;
    }
    return a;
}

unsigned short sub(unsigned short sub1, unsigned short sub2) {
    unsigned short s1 = sub1 & 0b1111111111111;
    unsigned short s2 = sub2 & 0b1111111111111;
    unsigned short ret;
    ret = (s1 - s2) & 0b1111111111111;
    return ret;
}

unsigned short mul(unsigned short mul1, unsigned short mul2) {
    return (mul1 * mul2) & 0b1111111111111;
}

Div division(unsigned short div1, unsigned short div2) {
    Div d;
    d.Q = (unsigned short)(div1 / div2);
    d.R = (unsigned short)(div1 % div2);
    return d;
}
